package com.geekaca.news.controller.admin;

import com.geekaca.news.domain.News;
import com.geekaca.news.domain.NewsCategory;
import com.geekaca.news.service.CategoryService;
import com.geekaca.news.service.NewsService;
import com.geekaca.news.utils.NewsConstants;
import com.geekaca.news.utils.PageResult;
import com.geekaca.news.utils.Result;
import com.geekaca.news.utils.ResultGenerator;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/admin")
public class BlogController {
    @Resource
    private NewsService blogService;
    @Resource
    private CategoryService categoryService;
    @Autowired
    private JedisPool jedisPool;


    @GetMapping("/blogs")
    public String list(HttpServletRequest request) {
        //为了传递值给前端页面 ，页面根据他来决定左侧导航菜单高亮显示哪个
        request.setAttribute("path", "blogs");
        //指向thymeleaf页面   blog.html页面内部通过JS 发送请求 获取数据
        return "admin/blog";
    }

    @GetMapping("/blogs/edit")
    public String blogEditNew(HttpServletRequest request) {
        //指向页面
        request.setAttribute("path", "blogs/edit");
//        List<NewsCategory> allCategories = categoryService.getAllCategories(null, null);

        // 尝试从 redis 缓存读取 类别
        Jedis jedis = jedisPool.getResource();
        Gson gson = new Gson();
        List<String> allCategoriesStr = jedis.lrange("categoryList", 0, jedis.llen("categoryList"));
        List<NewsCategory> allCategories = new ArrayList<>();
        allCategoriesStr.forEach(catStr->{
            allCategories.add(gson.fromJson(catStr,NewsCategory.class));
        });

        System.out.println("allCategories: " + allCategories);
        request.setAttribute("categories", allCategories);
        return "admin/edit";
    }

    @GetMapping("/blogs/edit/{id}")
    public String blogEdit(@PathVariable(name = "id", required = false) Integer id, HttpServletRequest request) {
        //指向页面
        System.out.println("url param: id=" + id);
        if (id == null) {
            return "admin/edit";
        } else {
//            List<NewsCategory> allCategories = categoryService.getAllCategories(null, null);
            // 尝试从 redis 缓存读取 类别
            Jedis jedis = jedisPool.getResource();
            Gson gson = new Gson();
            List<String> allCategoriesStr = jedis.lrange("categoryList", 0, jedis.llen("categoryList"));
            List<NewsCategory> allCategories = new ArrayList<>();
            allCategoriesStr.forEach(catStr->{
                allCategories.add(gson.fromJson(catStr,NewsCategory.class));
            });

            System.out.println("allCategories: " + allCategories);
            request.setAttribute("categories", allCategories);
            News blog = blogService.selectNewsAndCommentById(id.longValue());
            request.setAttribute("blog", blog);
            return "admin/edit";
        }
    }

    // 后台获取新闻列表
    @GetMapping("/blogs/list")
    @ResponseBody // 确保返回值为json
    public Result blogList(@RequestParam("page") Integer page, @RequestParam("limit") Integer limit,
                           @RequestParam(value = "keyword", required = false) String keyword, HttpServletRequest request) {
        /**
         * todo:
         * 分页查询
         *  1，先查询符合条件的总记录条数
         *  2， 查询符合条件的当前页数据list
         *
         * 查询所有新闻列表
         */
        if (page == null) {
            page = 1;
        }
        if (limit == null) {
            limit = 10;
        }

        //查询记录条数
        int allNewsCount = blogService.getAllNewsCount(keyword);
        List<News> newsList = blogService.getAllNews(page, limit, keyword);

        /*newsList.forEach(news -> {
            String url = news.getNewsCoverImage();
            String localAddr = "";
            if (url.contains("/uploadfile")) {
                String[] url_ = url.split("/uploadfile");
                String shortUrl = "/uploadfile" + url_[url_.length - 1];
                try {
                    localAddr = InetAddress.getLocalHost().getHostAddress();
                    localAddr = "http://"  + localAddr +":" + request.getServerPort() + shortUrl;
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
            } else {
                String[] url_ = url.split("/admin");
                String shortUrl = "/admin" + url_[url_.length - 1];
                try {
                    localAddr = InetAddress.getLocalHost().getHostAddress();
                    localAddr = "http://"  + localAddr +":" + request.getServerPort() + shortUrl;
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
            }

            news.setNewsCoverImage(localAddr);
        });
*/
        Result rs = new Result();
        rs.setResultCode(NewsConstants.RESULT_OK);
        PageResult pageResult = new PageResult(newsList, allNewsCount, limit, page);

        rs.setData(pageResult);
        return rs;
    }

    @PostMapping("/blogs/save")
    @ResponseBody
    public Result addNews(@RequestParam("blogTitle") String blogTitle,
                          @RequestParam(name = "blogSubUrl", required = false) String blogSubUrl,
                          @RequestParam("blogCategoryId") Integer blogCategoryId,
                          @RequestParam("blogTags") String blogTags,
                          @RequestParam("blogContent") String blogContent,
                          @RequestParam("blogCoverImage") String blogCoverImage,
                          @RequestParam("blogStatus") Integer blogStatus,
                          @RequestParam("enableComment") Integer enableComment) {
        if (!StringUtils.hasText(blogTitle)) {
            return ResultGenerator.genFailResult("请输入文章标题");
        }
        if (blogTitle.trim().length() > 150) {
            return ResultGenerator.genFailResult("标题过长");
        }
        if (!StringUtils.hasText(blogTags)) {
            return ResultGenerator.genFailResult("请输入文章标签");
        }
        if (blogTags.trim().length() > 150) {
            return ResultGenerator.genFailResult("标签过长");
        }
        if (blogSubUrl.trim().length() > 150) {
            return ResultGenerator.genFailResult("路径过长");
        }
        if (!StringUtils.hasText(blogContent)) {
            return ResultGenerator.genFailResult("请输入文章内容");
        }
        if (blogTags.trim().length() > 100000) {
            return ResultGenerator.genFailResult("文章内容过长");
        }
        if (!StringUtils.hasText(blogCoverImage)) {
            return ResultGenerator.genFailResult("封面图不能为空");
        }
        News news = new News();
        news.setNewsTitle(blogTitle);
        news.setNewsSubUrl(blogSubUrl);
        news.setNewsCategoryId(blogCategoryId);
        news.setNewsTags(blogTags);
        news.setNewsContent(blogContent);

        news.setNewsCoverImage(blogCoverImage);
        news.setNewsStatus(blogStatus);
        news.setEnableComment(enableComment);
        news.setCreateTime(new Date());
        news.setUpdateTime(new Date());
        news.setNewsViews(0L);
        // 如果是新增，调用新增，如果是修改，调用update语句
        News selectedNews = blogService.getById(news.getNewsId());
        // 新增的情形

        int updated = blogService.addNews(news);
        if (updated > 0) {
            return ResultGenerator.genSuccessResult("新增成功");
        } else {
            return ResultGenerator.genFailResult("新增失败");
        }
    }

    @PostMapping("/blogs/update")
    @ResponseBody
    public Result updateNews(@RequestParam("blogId") Long blogId,
                             @RequestParam("blogTitle") String blogTitle,
                             @RequestParam(name = "blogSubUrl", required = false) String blogSubUrl,
                             @RequestParam("blogCategoryId") Integer blogCategoryId,
                             @RequestParam("blogTags") String blogTags,
                             @RequestParam("blogContent") String blogContent,
                             @RequestParam("blogCoverImage") String blogCoverImage,
                             @RequestParam("blogStatus") Integer blogStatus,
                             @RequestParam("enableComment") Integer enableComment
    ) {
        if (!StringUtils.hasText(blogTitle)) {
            return ResultGenerator.genFailResult("请输入文章标题");
        }
        if (blogTitle.trim().length() > 150) {
            return ResultGenerator.genFailResult("标题过长");
        }
        if (!StringUtils.hasText(blogTags)) {
            return ResultGenerator.genFailResult("请输入文章标签");
        }
        if (blogTags.trim().length() > 150) {
            return ResultGenerator.genFailResult("标签过长");
        }
        if (blogSubUrl.trim().length() > 150) {
            return ResultGenerator.genFailResult("路径过长");
        }
        if (!StringUtils.hasText(blogContent)) {
            return ResultGenerator.genFailResult("请输入文章内容");
        }
        if (blogTags.trim().length() > 100000) {
            return ResultGenerator.genFailResult("文章内容过长");
        }
        if (!StringUtils.hasText(blogCoverImage)) {
            return ResultGenerator.genFailResult("封面图不能为空");
        }
        News news = new News();
        news.setNewsId(blogId);
        news.setNewsTitle(blogTitle);
        news.setNewsSubUrl(blogSubUrl);
        news.setNewsCategoryId(blogCategoryId);
        news.setNewsTags(blogTags);
        news.setNewsContent(blogContent);
        news.setNewsCoverImage(blogCoverImage);
        news.setNewsStatus(blogStatus);
        news.setEnableComment(enableComment);
        news.setCreateTime(new Date());
        news.setUpdateTime(new Date());
        news.setNewsViews(0L);

        int updated = blogService.updateNews(news);
        if (updated > 0) {
            return ResultGenerator.genSuccessResult("更新成功");
        } else {
            return ResultGenerator.genFailResult("更新失败");
        }
    }

    @PostMapping("/blogs/delete")
    @ResponseBody
    public Result deleteNews(@RequestBody List<Long> ids) {
        System.out.println(ids);
        Result result = new Result();

        int i = blogService.deleteNews(ids);
        if (i > 0) {
            result.setResultCode(NewsConstants.RESULT_OK);
            result.setMessage("删除成功");
        } else {
            result.setResultCode(NewsConstants.RESULT_FAIL);
            result.setMessage("删除失败");
        }

//        ids.forEach(id -> {
//            int i = blogService.deleteNews(id);
//            if (i > 0) {
//                result.setResultCode(NewsConstants.RESULT_OK);
//                result.setMessage("删除成功");
//            } else {
//                result.setResultCode(NewsConstants.RESULT_FAIL);
//                result.setMessage("删除失败");
//            }
//        });
        return result;
    }

    @PostMapping("/upload/file")
    @ResponseBody
    public Result uploadFile(@RequestParam("file") MultipartFile fileUpload) {
        System.out.println("upload....");
        Result rs = new Result();
        String fileName = fileUpload.getOriginalFilename();

        String tmpFilePath = NewsConstants.UPLOAD_PATH;
        String dataPath = "/uploadfile/" + fileName;

//        String resourcesPath = tmpFilePath;
        File upFile = new File(tmpFilePath, fileName);
        try {
            fileUpload.transferTo(upFile);
            rs.setResultCode(NewsConstants.RESULT_OK);
            rs.setData(dataPath);
            rs.setMessage("图片上传成功");

        } catch (IOException e) {
            rs.setResultCode(NewsConstants.RESULT_FAIL);
            rs.setMessage("图片上传失败");
            e.printStackTrace();
        }
        return rs;
    }

}
